package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.example.authforcmcc.AuthForCmcc;
import com.example.authforcmcc.Global;

import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class WebauthTestWidget extends GeneralTestWidget {

    private Activity ctx;
    private final Handler handler;
    private WebAuthManager webAuthManager;
    private WlanManager wlanManager;
    private Button btnback;
    private Button btnRetest;
    private int frequency = 2;
    private int current;
    private String defaultUrl;
    private LinearLayout webAuthLayout;
    private LinearLayout webauthTestChartLayout;
    private ScrollView sv;
    private boolean processing;
    private float loginTotalTime;
    private float logoutTotalTime;
    private int lsuccessTimes;
    private int osuccessTimes;
    //private ImageView pointImageView;
	//private TextView timesView;
	//private TextView timeRateView;
	//private TextView sucRateView;
    private double xdata[];
    private double lydata[];
    private double oydata[];
    private boolean logouting = false;
    private String username  = "";
    private String password = "";
    private int testedTime1=0;
    private static String TAG = "WebauthTestWidget";
    private ProgressBar pb;
    private TextView webauth_test;
//    private EditText userNameEt;
//    private EditText pwdEt;
//    private Button btnStart;
    private int testedTimes;
    private boolean loginSucess = false;
    private AuthForCmcc authForCmcc;

    private Task task;
    private String fileName;
    
    private boolean firstSucess;

    public WebauthTestWidget(Activity context) {
        super(context);
        this.ctx = context;
        inflate(context, R.layout.webauth_test_widget, this);
        btnback = (Button) this.findViewById(R.id.webauth_test_btnback);
        
     //   btnRetest = (Button) this.findViewById(R.id.btn_webauth_retest);
        webauth_test = (TextView)this.findViewById(R.id.webauth_test);
        defaultUrl = ctx.getResources().getString(R.string.default_url);
        sv = (ScrollView) this.findViewById(R.id.webauth_test_ScrView);
        webAuthLayout = (LinearLayout) this.findViewById(R.id.webauth_test_layout);
        webauthTestChartLayout = (LinearLayout) this.findViewById(R.id.webauthTestChartLayout);
        pb = (ProgressBar)findViewById(R.id.web_auth_progress);
        pb.setMax(frequency * 2);
        xdata = new double[frequency];
        lydata = new double[frequency];
        oydata = new double[frequency];
        drawChart();
       // userNameEt = (EditText) this.findViewById(R.id.userNameEditText);
      //  pwdEt = (EditText) this.findViewById(R.id.pwdEditText);
//        btnStart = (Button) this.findViewById(R.id.btn_webauth_start);

        //pointImageView = (ImageView)findViewById(R.id.pointImageView);
        /*timeRateView = (TextView)findViewById(R.id.timeRateView);
        timesView = (TextView)findViewById(R.id.timesView);
        sucRateView = (TextView)findViewById(R.id.sucRateView);
        timeRateView.setText("0 %");
        timesView.setText(testedTimes + "/"+frequency*2+"次");
        sucRateView.setText("0 %");*/
        btnback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) { 
            	switch(GlobalApp.nowNetType) {
				case 1:
					backToTestWidget_Wlan(ctx);
					break;
				case 2:
					backToTestWidget_TD(ctx);
					break;
				case 3:
					backToTestWidget_GSM(ctx);
					break;
				default:
					break;
				}
            } 
        });

       /* btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // WebauthTestWidget ww = new WebauthTestWidget(ctx);
                // ctx.setContentView(ww);
                if (null != fileName) {
                //    new UploadResultTask().execute();         //////////////////////////////////
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
            }
        });*/

        /*btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });*/

        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    showWifiListDialog(ctx, wlanManager, handler);
                    dismissMessageDialog();
                    wlanManager.stopScan();
                    break;
                case MessageWhat.WIFI_SELECTED:
                    enableNetWork(selectedScanResult);
                    break;
                case MessageWhat.WIFI_SUCESS_CONNECTED:
                    dismissMessageDialog();
                    start();
                    break;
                case MessageWhat.WEB_AUTH_LOGIN:
                	if (current<frequency) {
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						current ++;
						webAuthManager.setStartTime(System.currentTimeMillis());
						authForCmcc.startAuth();
					}else {
						handler.sendEmptyMessage(MessageWhat.DONE);
					}
                	break;
                case MessageWhat.WEB_AUTH_LOGOUT:
                	webAuthManager.setStartTime(System.currentTimeMillis());
                	if (loginSucess) {
						authForCmcc.logoutcmcc();
					}else {
						handler.sendEmptyMessage(MessageWhat.LOGOUT_FAILED);
					}
                	break;
                default:
                    update(msg.what);
                }
            }
        };
        webAuthManager = new WebAuthManager(ctx);
        webAuthManager.setHandler(handler);
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler); 
        task = new Task();
        DBManager db = new DBManager(ctx);
		Account config = db.getAccount();
		if(null != config){
//			userNameEt.setText(config.userName);
//			pwdEt.setText(config.password);
			username = config.userName;
			password = config.password;
	        scanWifi();
		}else {
			showMessage(ctx, "请至系统管理配置CMCC账号"); 
		}
		db.release();
    }

    private void scanWifi() {
        this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    private void enableNetWork(final ScanResult scan) {
        this.showMessageDialog(ctx, "正在连接Wifi...");
    	System.err.println(scan.SSID);
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

    }

    private void update(int what) {
        testedTimes++;
        this.setDialogProgress(testedTimes);
        DecimalFormat df = new DecimalFormat("#0.000");
        StringBuffer s = new StringBuffer();
        System.err.println(current+"==========================current");
        webAuthManager.setEndTime(System.currentTimeMillis());
        if (current>0) {
        	 xdata[current - 1] = current;
             float costTime = (webAuthManager.getEndTime() - webAuthManager.getStartTime()) / (float)1000;
             if (MessageWhat.LOGIN_SUCCESS == what) {
            	 
				if (current == 1) {
					firstSucess = true;
				}
				
				if (current == 1 || ( current == 2 && !firstSucess) ) {
					s.append("加载认证页面时延：")
					.append(df.format(authForCmcc.getLoadAuthTime()))
					.append('s').append("\n");
				}

				if (current == 1) {
					s.append("第").append(current).append("次 登录成功，时延：").append(df.format(costTime- authForCmcc.getLoadAuthTime())  ).append('s');
				}
				
				if (current == 2) {
					if (firstSucess) {
						s.append("第").append(current).append("次 登录成功，时延：").append(df.format(costTime) ).append('s');
					}else {
						s.append("第").append(current).append("次 登录成功，时延：").append(df.format(costTime- authForCmcc.getLoadAuthTime())  ).append('s');
					}
				}
				
                 loginTotalTime += costTime;
                 lydata[current - 1] = costTime;
                 lsuccessTimes++;
                 TextView tv = new TextView(ctx);
                 tv.setTextSize(12);
                 tv.setText(s);
                 tv.setTextColor(Color.BLACK);
                 webAuthLayout.addView(tv);
                 updateProgressBar(testedTimes);
                 loginSucess = true;
                 handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGOUT);
             } else if (MessageWhat.LOGOUT_SUCCESS == what) {
                 s.append("第").append(current).append("次 下线成功，时延：").append(df.format(costTime)).append('s');
                 logoutTotalTime += costTime;
                 oydata[current - 1] = costTime;
                 osuccessTimes++;
                 TextView tv = new TextView(ctx);
                 tv.setTextSize(12);
                 tv.setText(s);
                 tv.setTextColor(Color.BLACK);
                 webAuthLayout.addView(tv);
                 updateProgressBar(testedTimes);
                 handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGIN);
             } else if (what == MessageWhat.LOGIN_FAILED) {
                 s.append("第").append(current).append("次 登录失败");
                 lydata[current - 1] = 0;
                 TextView tv = new TextView(ctx);
                 tv.setTextSize(12);
                 tv.setText(s);
                 tv.setTextColor(Color.BLACK);
                 webAuthLayout.addView(tv);
                 updateProgressBar(testedTimes);
                 if (current == 0) {
					firstSucess = false;
				}
                 loginSucess = false;
                 handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGOUT);
             } else if (what == MessageWhat.LOGOUT_FAILED) {
                 s.append("第").append(current).append("次 下线失败");
                 oydata[current - 1] = 0;
                 TextView tv = new TextView(ctx);
                 tv.setTextSize(12);
                 tv.setText(s);
                 tv.setTextColor(Color.BLACK);
                 webAuthLayout.addView(tv);
                 updateProgressBar(testedTimes);
                 handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGIN);
             }
             if (MessageWhat.DONE == what) {
            	 webauth_test.setText("测试完毕");
                 float lavg = (lsuccessTimes == 0) ? 0 : loginTotalTime / (float)lsuccessTimes;
                 // long oavg = (osuccessTimes == 0) ? 0 : logoutTotalTime /
                 // osuccessTimes;
                 float sucessRate = ((float) lsuccessTimes / frequency) * 100;
                 float offSuccessRate = ((float) osuccessTimes / frequency) * 100;
                 s = new StringBuffer();
                 s.append("认证次数：").append(frequency).append("次; ");
                 s.append("成功次数：").append(lsuccessTimes).append('次').append('\n');
                 s.append("认证平均时延：").append(df.format(lavg)).append('s').append('\n');
                 s.append("认证成功率：").append(sucessRate).append('%').append(" 下线成功率：").append(offSuccessRate).append('%');
                 TextView tv = new TextView(ctx);
                 tv.setTextSize(13);
                 tv.setTextColor(Color.BLUE);
                 tv.setText(s);
                 webAuthLayout.addView(tv);
                 drawChart();

                 task.endTime = StringUtils.getDateTime();
                 task.webDelay = String.valueOf(lavg);
                 task.webSuccessRate = String.valueOf(sucessRate);
                 task.webOffSuccessRate = String.valueOf(offSuccessRate);
                 dismissProgressDialog();
                 Global.AuthString = null;
             }
             this.setScrollViewDown(sv);
             processing = false;
		}
    }

    private void updateProgressBar(int current) {
    	pb.setProgress(current);
    }
    
    private void drawChart() {
        webauthTestChartLayout.removeAllViews();
        int max = getMax(lydata)>getMax(oydata) ? getMax(lydata):getMax(oydata);
        ChartManager cm = new ChartManager(ctx, 4, max);
        
        //ChartManager cm = new ChartManager(ctx, 10, 30);
        String chartTitle = "WEB登录认证/下线测试";
        String[] lineTitles = new String[] { "WEB登录认证测试", "WEB下线测试" };
        List<double[]> x = new ArrayList<double[]>(2);
        List<double[]> y = new ArrayList<double[]>(2);
        x.add(xdata);
        y.add(lydata);
        x.add(xdata);
        y.add(oydata);
        int[] colors = new int[] { Color.BLUE, Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        webauthTestChartLayout.addView(lineChart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        // 上传结果
     //   new UploadResultTask().execute();     /////////////////////////////////////////

    }


    private void clear() {
        testedTimes = 0;
        current = 0;
        loginTotalTime = 0;
        logoutTotalTime = 0;
        lsuccessTimes = 0;
        osuccessTimes = 0;
        xdata = null;
        lydata = null;
        oydata = null;
        processing = false;
        webAuthLayout.removeAllViews();
    }

   
	public void start() {
		final String userName = username;
		final String pwd = password;
		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
			this.showMessage(ctx, "请配置CMCC账号或密码.");
			return;
		}
		clear();

		updateProgressBar(0);
		initTask(task, ctx, ConnectivityManager.TYPE_WIFI);
		task.startTime = StringUtils.getDateTime();
		xdata = new double[frequency];
		lydata = new double[frequency];
		oydata = new double[frequency];
		oydata = new double[frequency];
		authForCmcc = new AuthForCmcc(ctx, handler, userName, pwd);
			
		new Thread() {
			public void run() {
				webAuthManager.logout2();
				firstSucess = false;
				handler.sendEmptyMessage(MessageWhat.WEB_AUTH_LOGIN);
			}
		}.start();
		
	}

    private void printInfo(boolean b ,boolean login) {
    	if(login) {
    		if(b) {
    			System.out.println("------ 认证 成功");
    		} else {
    			System.out.println("------ 认证 失败");
    		}
    	} else {
    		if(b) {
    			System.out.println("------ 下线 成功");
    		} else {
    			System.out.println("------ 下线 失败");
    		}
    	}
    }
 
   /* public void rotateDialChart(int current,int frequency){
		
 		float start = current ==0?0:(float)(current-1)/frequency*180;
 		float end = (float)current/frequency*180;
 	// 旋转动画效果 
 		 AnimationSet animation=new AnimationSet(true);
 		 RotateAnimation rotateAnimation=new RotateAnimation(start, end,
 				Animation.RELATIVE_TO_SELF, 1f,
 				Animation.RELATIVE_TO_SELF, 0.25f);
 	//	AlphaAnimation alpha=new AlphaAnimation(1, 0);
 		 ScaleAnimation acale=new ScaleAnimation(1, 0.1f, 1,0.1f,
 				 Animation.RELATIVE_TO_SELF, 0.5f,
 				 Animation.RELATIVE_TO_SELF, 0.5f);
 			acale.setDuration(1000);
 			animation.addAnimation(acale);
 		 rotateAnimation.setDuration(500);
 		 animation.addAnimation(rotateAnimation);
 		 animation.setFillEnabled(true);
 		 animation.setFillAfter(true);
 	//	 alpha.setDuration(3000);
 	//	 animation.addAnimation(alpha);
 		 pointImageView.startAnimation(animation); 
 	}*/
}
